/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.service.cacheplugins  
 */
package com.apache.bid.service.cacheplugins;

import java.math.BigDecimal;
import java.util.List;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.TeaUtil;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.cache.BidDataBaseRunable;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidInfoBaojia;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidItemVip;
import com.apache.cache.util.Validator;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  份额竞价提交方法(价格优先，时间优先)
 * @author Hou Dayu 创建时间：2016-3-28  
 * 
 */
public class ShareSavePluginImpl implements PluginConnector {

	/**
	 * TODO 此竞价方式处理还有问题如bidNum ,价格计算等
	 * @see com.zbxsoft.api.manager.PluginConnector#execute(com.zbxsoft.api.vo.ParamsVo)  
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object execute(ParamsVo param) throws Exception {
		ResultEntity entity = new ResultEntity();
		String objId = String.valueOf(param.getParams("syncObjId"));
		Constant.getInstance().setJingjiaMap(objId, objId);
		final String key = Constant.getInstance().getJingjiaMap(objId);
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		synchronized (key) {//加入同步锁
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
			String itemId = String.valueOf(param.getParams("itemId"));
			String userEname = String.valueOf(param.getParams("userEname"));
			String myPrice = String.valueOf(param.getParams("myPrice"));
			param.setParams("bidTime", bidTime);
			BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheObjectByKey(cache.item_prefix + itemId);
			String applyKey = "";
			if (Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemId;
			} else {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemVo.getSessionId();
			}
			BidApply apply = (BidApply) cache.getCacheObjectByKey(applyKey);
			String vipKey = BidCacheManager.item_vip_prefix + userEname + "_" + itemId;
			BidItemVip vip = (BidItemVip) cache.getCacheObjectByKey(vipKey);
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
			String myPriceStr = TeaUtil.decryptByTea(myPrice);
			ResultMsg msg = BidCommonUtil.getInstance().getCheckItem(status, myPriceStr, userEname, itemVo, price);
			if (!ToolsUtil.isEmpty(msg)) {
				entity.setResult("false");
				entity.setEntity("F".equals(msg.getFlag()) ? "false" : "true");
				entity.setMessage(msg.getMsg());
				return entity;
			}
			//			String itemStatus = String.valueOf(param.getParams("itemStatus"));
			//			if (status.equals(itemStatus) && Constant.getInstance().getItemConfig("exercise").equals(status)) {//行权期
			//				return exerciseItem(param, price, itemVo, apply, vip);
			//			}
			if (Constant.getInstance().getItemConfig("exercise").equals(status)) {
				entity.setResult("false");
				entity.setEntity("false");
				entity.setMessage("标的不在行权期");
				return entity;
			}
			String bjKey = BidCacheManager.baojia_prefix + userEname + "_" + itemId;
			List<BidInfoBaojia> bjList = (List<BidInfoBaojia>) cache.getCacheCloneByKey(bjKey);
			String bidId = String.valueOf(param.getParams("bidId"));
			if (!Validator.isEmpty(bjList) && Validator.isNotNull(bidId)) {
				for (BidInfoBaojia bjVo : bjList) {
					if (!bidId.equals(bjVo.getBidId())) {
						continue;
					}
					if ("0".equals(Validator.getDefaultStr(itemVo.getAllowUpdateTimes(), "0"))) {//允许修改报价的次数（bidmode=3/4使用）（缺省=0不允许修改）
						entity.setResult("false");
						entity.setEntity("false");
						entity.setMessage("您已报过价，不能修改报价信息");
						return entity;
					}
					int ifUpdateTimes = Integer.parseInt(itemVo.getAllowUpdateTimes());
					int updateTimes = Integer.parseInt(Validator.getDefaultStr(bjVo.getUpdateTimes(), "0"));
					if (updateTimes > ifUpdateTimes) {
						entity.setResult("false");
						entity.setEntity("false");
						entity.setMessage("您已超过允许修改的次数，不能修改报价信息");
						return entity;
					}
					break;
				}
			}
			boolean mark = exeBaojia(param, price, itemVo, apply, vip, bjList);
			if (mark) {
				entity.setResult("true");
				entity.setEntity("true");
				entity.setMessage("报价成功");
			} else {
				entity.setResult("false");
				entity.setEntity("false");
				entity.setMessage("报价失败");
			}
		}
		return entity;
	}

	private boolean exeBaojia(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip, List<BidInfoBaojia> bjList) throws Exception {
		ResultEntity entity = new ResultEntity();
		String itemId = String.valueOf(param.getParams("itemId"));
		String userEname = String.valueOf(param.getParams("userEname"));
		String myPrice = String.valueOf(param.getParams("myPrice"));
		String bidTime = String.valueOf(param.getParams("bidTime"));
		//String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();

		String bidNum = StrUtil.doNull(String.valueOf(param.getParams("bidNum")), "1");
		String userIp = String.valueOf(param.getParams("userIp"));
		String bidId = String.valueOf(param.getParams("bidId"));
		boolean mark = false;
		String exeType = "save";
		BidInfoBaojia bjVo = null;
		if (!Validator.isEmpty(bjList)) {//判断是否同一人报价
			if (Validator.isNull(bidId)) {
				bjVo = new BidInfoBaojia();
				bjVo.setUpdateTimes("0");
				bjVo.setBidValue(myPrice);
				bjVo.setUserIp(userIp);
				BigDecimal myPrices = new BigDecimal(TeaUtil.decryptByTea(myPrice));
				bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(itemVo.getFirstValuePre()))));
				bjVo.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(bidNum))));
				bjVo.setBidTime(bidTime);
				if (Validator.isEmpty(vip))
					bjVo.setRightLevel("0");
				else
					bjVo.setRightLevel(vip.getVipLevel());
				bjVo.setUserName(userEname);
				bjVo.setUserId(apply.getUserId());
				bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(price.getFirstValue()))));
				bjVo.setBidId(Validator.generate());
				bjVo.setItemId(itemId);
				bjVo.setBidNum(bidNum);
				mark = BidCacheFactory.getInstance().getCacheManager("baojia").createCacheObject(bjVo);
			} else {
				for (BidInfoBaojia bj : bjList) {//处理修改报价的信息
					if (!bidId.equals(bj.getBidId())) {
						continue;
					}
					int updateTimes = Integer.parseInt(Validator.getDefaultStr(bj.getUpdateTimes(), "0"));
					bj.setUpdateTimes(String.valueOf(updateTimes + 1));
					bj.setBidValue(myPrice);
					bj.setUserIp(userIp);
					BigDecimal myPrices = new BigDecimal(TeaUtil.decryptByTea(myPrice));
					bj.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(itemVo.getFirstValuePre()))));
					bj.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(bidNum))));
					bj.setBidTime(bidTime);
					bjVo = bj;
					break;
				}
				String bjKey = BidCacheManager.baojia_prefix + userEname + "_" + itemId;
				mark = BidCacheFactory.getInstance().getCacheManager("baojia").updateCacheObject(bjKey, bjVo);
				exeType = "save";
			}
		} else {
			bjVo = new BidInfoBaojia();
			bjVo.setUpdateTimes("0");
			bjVo.setBidValue(myPrice);
			bjVo.setUserIp(userIp);
			BigDecimal myPrices = new BigDecimal(TeaUtil.decryptByTea(myPrice));
			bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(itemVo.getFirstValuePre()))));
			bjVo.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(bidNum))));
			bjVo.setBidTime(bidTime);
			if (Validator.isEmpty(vip))
				bjVo.setRightLevel("0");
			else
				bjVo.setRightLevel(vip.getVipLevel());
			bjVo.setUserName(userEname);
			bjVo.setUserId(apply.getUserId());
			bjVo.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(price.getFirstValue()))));
			bjVo.setBidId(Validator.generate());
			bjVo.setItemId(itemId);
			bjVo.setBidNum(bidNum);
			mark = BidCacheFactory.getInstance().getCacheManager("baojia").createCacheObject(bjVo);
		}
		ParamsVo<BidInfoBaojia> vo = new ParamsVo<BidInfoBaojia>();
		vo.setObj(bjVo);
		BidDataBaseRunable runable = new BidDataBaseRunable(vo, "bidInfoBaojiaManager", exeType);
		BidCacheFactory.getInstance().exeDatabase(runable);
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("报价成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("报价失败");
		}
		return mark;
	}

	/**
	 * description:  行权期
	 * @throws Exception 
	 */
	private ResultEntity exerciseItem(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip) throws Exception {
		ResultEntity entity = new ResultEntity();
		if (!"e".equals(vip.getVipType())) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("您无权行权");
			return entity;
		}
		boolean mark = exeBaojia(param, price, itemVo, apply, vip, null);
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("行权成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("行权失败");
		}
		return entity;
	}

}
